package com.zsr.example.controller.front;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.entity.*;
import com.zsr.example.service.*;
import com.zsr.example.service.impl.IndexFrontServiceImpl;
import com.zsr.example.util.CommonUtil;
import com.zsr.example.util.JwtUtil;
import com.zsr.example.util.constants.ErrorEnum;
import com.zsr.example.util.constants.SysConstants;
import com.zsr.example.vo.SubjectNestedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 首页查询接口
 *
 * @author zsr
 * @date 2021/6/18 10:46
 */
@RestController
@RequestMapping("/eduservice/indexfront")
@CrossOrigin
public class IndexController {
    //（1）查询最新前4条讲师数据
    //（2）查询最新前8条课程数据
    @Autowired
    private IndexFrontServiceImpl indexFrontService;
    @Autowired
    private CrmBannerService bannerService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private EduArticleService articleService;
    @Autowired
    private EduPathService pathService;
    @Autowired
    private EduCommentService commentService;
    @Autowired
    private TChatRecordService chatRecordService;
    @Autowired
    private SysDictItemService sysDictItemService;

    //查询前8条热门课程，查询前4条名师
    @GetMapping("index")
    public JSONObject index() {
        //StopWatch stopWatch = new StopWatch();
        // 开始时间
        //stopWatch.start();
        //查询前8条热门课程
        List<EduCourse> courseList = indexFrontService.getHotCourseList();

        //查询前4条名师
        List<EduTeacher> teacherList = indexFrontService.getFourTeacherList();

        //查询分类
        List<SubjectNestedVo> subjectList = indexFrontService.getSubjectNestedList(5L);

        //查询banner
        List<CrmBanner> bannerList = bannerService.selectAllBanner();

        //查询图文
        List<EduArticle> articleList = articleService.getFourList();

        // 查询路径
        List<EduPath> pathList = pathService.getIndexList();

        Map<String, Object> map = new HashMap<>();
        map.put("courseList", courseList);
        map.put("teacherList", teacherList);
        map.put("subjectList", subjectList);
        map.put("bannerList", bannerList);
        map.put("articleList", articleList);
        map.put("pathList", pathList);
        // 结束时间
        //stopWatch.stop();
        // 统计执行时间（秒）Argument type 'double' does not match the type of the format specifier '%d'
        //System.out.printf("执行时长：%f 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 为换行

        //0.949157 秒
        return CommonUtil.successJson(map);
    }

    /**
     * 根据关键字搜索课程
     *
     * @param keyword
     * @return
     */
    @GetMapping("searchByKeyWord/{page}/{limit}/{keyword}")
    public JSONObject searchByKeyWord(@PathVariable long page, @PathVariable long limit,
                                      @PathVariable String keyword) {
        Page<EduCourse> pageCourse = new Page<>(page, limit);
        Map<String, Object> result = indexFrontService.searchByKeyWord(pageCourse, keyword);
        return CommonUtil.successJson(result);
    }

    /**
     * 热搜排行榜
     *
     * @return
     */
    @GetMapping("/queryTopSearchHotWord")
    public JSONObject testQueryTopSearchHotWord(/*@RequestParam("start") Integer start,
                                              @RequestParam("end") Integer end*/) {
        //查看redis有序集合的命令：ZRANGE  searchHotWord 0 11 WITHSCORES
        Set<ZSetOperations.TypedTuple<String>> resultSet = redisService.queryTopSearchHotWord(0, 9);
        //TODO 每日清除排行榜
        return CommonUtil.successJson(resultSet);
    }

    @GetMapping("/msgCount")
    public JSONObject getMsgCount(HttpServletRequest request) {
        String uId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(uId)) return CommonUtil.successJson();
        return CommonUtil.successJson(indexFrontService.getMsgCount(uId));
    }
@GetMapping("/getWebInfo")
public JSONObject getWebInfo(){
    List<SysDictItem> site = sysDictItemService.list(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictCode, "site"));
    Map<String, String> maps = site.stream().collect(Collectors.toMap(SysDictItem::getItemKey, SysDictItem::getItemValue, (key1, key2) -> key2));
    return CommonUtil.successJson(maps);
}

    /**
     * 获取消息通知
     *
     * @return
     */
    @GetMapping("/msg")
    public JSONObject getMsg(HttpServletRequest request) {
        String uId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(uId)) return CommonUtil.successJson();
        HashMap<String, Object> result = new HashMap<>();
        List<EduComment> replyList = commentService.getMyReplyMsg(uId);
        List<TChatRecord> chatList = chatRecordService.getMyChat(uId);
        result.put("replyList", replyList);
        result.put("chatList", chatList);
        return CommonUtil.successJson(result);
    }

    @GetMapping("/doRead")
    @Transactional
    public JSONObject doRead(HttpServletRequest request) {
        String uId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(uId)) throw new CommonJsonException(ErrorEnum.E_20001);
        indexFrontService.doRead(uId);
        return CommonUtil.successJson();
    }
    @PostMapping("/doChat")
    @Transactional
    public JSONObject doChat(HttpServletRequest request,@RequestBody TChatRecord chatRecord) {
        String uId = JwtUtil.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(uId)) throw new CommonJsonException(ErrorEnum.E_20001);
        chatRecord.setFromMemberId(uId);
        chatRecord.setStatus(SysConstants.STATUS_NO_READ);
        chatRecordService.save(chatRecord);
        return CommonUtil.successJson();
    }

    /*@GetMapping("tj")
    public JSONObject tj(){
        return  CommonUtil.successJson(tongJiApiService.getTimeTrendRpt());
    }

    @GetMapping("test")
    public JSONObject test() {
        throw new CommonJsonException("cc", "cc");
    }

    @GetMapping("test2")
    public JSONObject test2() {
        int i = 0;
        int r = 1 / i;
        return null;
    }*/

}
